package com.gyt.framework.common.utils;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @Author created by v_yantgao
 * @Date 2021/1/11 15:53
 */
public class HmacUtil {

    /**
     * 对参数进行hmac_sha256签名
     * @param paramMap
     * @return
     */
    public static String signHmacSha256(Map<String, String> paramMap, String token){
        String sign = null;
        List<String> tempList = mapToList(paramMap);
        String beforeSign = StringUtils.join(tempList, "&") + "&fappToken=" + token;
        sign = Base64.encodeBase64String(HmacUtils.hmacSha256(token, beforeSign)).toUpperCase();
        return sign;
    }

    private static List<String> mapToList(Map<String, String> paramMap) {
        List<String> tempList = new ArrayList<>();
        if(paramMap != null && paramMap.size() > 0){
            for(Map.Entry<String, String> entry : paramMap.entrySet()){
                String key = entry.getKey();
                if("sign".equals(key)){
                    continue;
                }
                String value = entry.getValue();
                if(StringUtils.isNotEmpty(key) && StringUtils.isNotEmpty(value)){
                    String temp = key + "=" + value;
                    tempList.add(temp);
                }
            }
        }
        Collections.sort(tempList);
        return tempList;
    }

}
